import { queryPage, queryInfoById, create, remove, update, allotRoles, queryRoleList } from './service';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'group',

  state: {
    list: { data: [] },
    details: [],
    cond: {}
  },

  effects: {
    *initCond(_, { put }) {
      yield put({ type: 'setCond', payload: {} });
      yield put({ type: 'queryPage' })
    },
    *updateCond({ payload }, { put }) {
      yield put({ type: 'setCond', payload });
      yield put({ type: 'queryPage' })
    },
    *queryPage({ payload = { pageNum: 1, pageSize: 10 } }, { call, put, select }) {
      const cond = yield select(state => state.group.cond);
      const params = { ...payload, ...cond };
      const { list = [], total } = yield call(queryPage, params);
      yield put({ type: 'setPage', payload: { list, total } })
    },
    *queryInfoById({ payload }, { call, put }) {
      const response = yield call(queryInfoById, payload);
      yield put({ type: 'setInfo', payload: response })
    },
    *queryEditInfoById({ payload }, { call, put }) {
      const response = yield call(queryInfoById, payload.id);
      const items = {};

      payload.keys.forEach(item => {
        items[item] = response[item]
      });
      yield put({ type: 'setEditInfo', payload: items })
    },
    *create({ payload }, { call, put }) {
      yield call(create, payload);
      yield put(routerRedux.push('/data/group'));
    },
    *update({ payload }, { call, put }) {
      yield call(update, payload);
      yield put(routerRedux.push('/data/group'));
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put(routerRedux.push('/data/group'));
    },
    *queryRoleList(_, { call, put }) {
      const response = yield call(queryRoleList);
      yield put({
        type: 'setRoleList',
        payload: response
      })
    },
    *queryAuthTree({ payload }, { put, take, select }) {

      yield put({ type: 'queryInfoById', payload: payload.id });
      yield put({ type: 'queryRoleList' });
      yield take('queryInfoById/@@end');
      const details = yield select(state => state.group.details);
      payload.callback(details);
    },
    *allotRoles({ payload }, { call, put }) {
      yield call(allotRoles, payload);
      yield put(routerRedux.push('/data/group'));
    },
  },

  reducers: {
    setCond(state, action) {
      return {
        ...state,
        cond: action.payload
      }
    },
    setPage(state, action) {
      return {
        ...state,
        list: {
          data: action.payload.list,
          dataCnt: action.payload.total
        }
      }
    },
    setInfo(state, action) {
      return {
        ...state,
        details: action.payload
      }
    },
    setEditInfo(state, action) {
      return {
        ...state,
        editDetails: action.payload
      }
    },
    setRoleList(state, action) {
      return {
        ...state,
        roles: action.payload
      }
    }
  }
}
